// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/service/module/thirdaccount_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"
	"gin-sns/app/common/github"
	"gin-sns/app/common/qq"
	"gin-sns/app/dao/module/thirdaccount"
	"gin-sns/app/model/constants"
	thirdaccountModel "gin-sns/app/model/module/thirdaccount"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/tools"
	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var ThirdaccountService = newThirdaccountService()

func newThirdaccountService() *thirdaccountService {
	return &thirdaccountService{}
}

type thirdaccountService struct {
}

//根据主键查询数据
func (s *thirdaccountService) SelectRecordById(id int64) (*thirdaccountModel.Entity, error) {
	return thirdaccount.ThirdaccountDao.SelectById(id)
}

//
func (s *thirdaccountService) SelectRecordsIn(idarr []int64) ([]thirdaccountModel.Entity, error) {

	list, err := thirdaccount.ThirdaccountDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *thirdaccountService) DeleteRecordById(id int64) bool {
	return thirdaccount.ThirdaccountDao.DeleteById(id)
}

//批量删除数据记录
func (s *thirdaccountService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := thirdaccount.ThirdaccountDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *thirdaccountService) AddSave(req *thirdaccountModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity thirdaccountModel.Entity

	//entity.Id = req.Id
	entity.UserId = req.UserId
	entity.Avatar = req.Avatar
	entity.Nickname = req.Nickname
	entity.ThirdType = req.ThirdType
	entity.ThirdId = req.ThirdId
	entity.ExtraData = req.ExtraData
	entity.Status = req.Status
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := thirdaccount.ThirdaccountDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *thirdaccountService) EditSave(req *thirdaccountModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &thirdaccountModel.Entity{Id: req.Id}
	ok, err := thirdaccount.ThirdaccountDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.UserId = req.UserId
	entity.Avatar = req.Avatar
	entity.Nickname = req.Nickname
	entity.ThirdType = req.ThirdType
	entity.ThirdId = req.ThirdId
	entity.ExtraData = req.ExtraData
	entity.Status = req.Status
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return thirdaccount.ThirdaccountDao.Update(entity)
}

//根据条件查询数据
func (s *thirdaccountService) SelectListAll(params *thirdaccountModel.SelectPageReq) ([]thirdaccountModel.Entity, error) {
	return thirdaccount.ThirdaccountDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *thirdaccountService) SelectListByPage(params *thirdaccountModel.SelectPageReq) ([]thirdaccountModel.Entity, *page.Paging, error) {
	return thirdaccount.ThirdaccountDao.SelectListByPage(params)
}

// 导出excel
func (s *thirdaccountService) Export(param *thirdaccountModel.SelectPageReq) (string, error) {
	head := []string{"", "用户id", "用户头像", "用户昵称", "帐号类型", "帐号id", "扩展数据", "0未审核 1正常状态 2审核未通过 3删除", "创建时间"}
	col := []string{"id", "user_id", "avatar", "nickname", "third_type", "third_id", "extra_data", "status", "create_time"}
	return thirdaccount.ThirdaccountDao.SelectListExport(param, head, col)
}

func (s *thirdaccountService) GetThirdAccount(thirdType string, thirdID string) (*thirdaccountModel.Entity, error) {
	entity := &thirdaccountModel.Entity{ThirdType: thirdType, ThirdId: thirdID}
	have, err := thirdaccount.ThirdaccountDao.FindOne(entity)
	if !have {
		err = errors.New("not found")
	}
	return entity, err
}

func (s *thirdaccountService) GetOrCreateByGithub(code, state string) (*thirdaccountModel.Entity, error) {
	userInfo, err := github.GetUserInfoByCode(code, state)
	if err != nil {
		return nil, err
	}

	account, _ := s.GetThirdAccount(constants.ThirdAccountTypeGithub, strconv.FormatInt(userInfo.Id, 10))
	if account != nil {
		return account, nil
	}

	nickname := userInfo.Login
	if len(userInfo.Name) > 0 {
		nickname = strings.TrimSpace(userInfo.Name)
	}

	userInfoJSON, _ := tools.FormatJson(userInfo)
	AddReq := &thirdaccountModel.AddReq{
		//UserId:    sql.NullInt64{},
		Avatar:    userInfo.AvatarUrl,
		Nickname:  nickname,
		ThirdType: constants.ThirdAccountTypeGithub,
		ThirdId:   strconv.FormatInt(userInfo.Id, 10),
		ExtraData: userInfoJSON,
	}
	_, err = s.AddSave(AddReq, nil)
	if err != nil {
		return nil, err
	}
	return account, nil
}

func (s *thirdaccountService) GetOrCreateByQQ(code, state string) (*thirdaccountModel.Entity, error) {
	userInfo, err := qq.GetUserInfoByCode(code, state)
	if err != nil {
		return nil, err
	}

	account, _ := s.GetThirdAccount(constants.ThirdAccountTypeQQ, userInfo.Unionid)
	if account != nil {
		return account, nil
	}

	userInfoJSON, _ := tools.FormatJson(userInfo)
	AddReq := &thirdaccountModel.AddReq{
		//UserId:    sql.NullInt64{},
		Avatar:    userInfo.FigureurlQQ1,
		Nickname:  strings.TrimSpace(userInfo.Nickname),
		ThirdType: constants.ThirdAccountTypeQQ,
		ThirdId:   userInfo.Unionid,
		ExtraData: userInfoJSON,
	}
	_, err = s.AddSave(AddReq, nil)
	if err != nil {
		return nil, err
	}
	return account, nil
}
